package io.codescience.aianaly.controller;

import io.codescience.aianaly.model.User;
import io.codescience.aianaly.repository.UserRepository;
import io.codescience.aianaly.utils.AuthUtil;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;


@Controller
@RequestMapping("/admin")
public class AdminController {
    private final UserRepository userRepository;
    private static final String DEFAULT_AVATAR = "/static/images/img_01.png"; // 默认头像路径

    private  static final String[] AVATAR_OPTIONS = {
        "/static/images/img_01.png",
        "/static/images/img_02.png",
        "/static/images/img_03.png",
        "/static/images/img_04.jpg",
        "/static/images/img_05.jpg",
        "/static/images/img_06.jpg",
        "/static/images/img_07.jpg",
    };

    public AdminController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    //权限检查中间方法
    private String checkAdminAndRedirect(HttpSession session) {
        return AuthUtil.checkAdminAndRedirect(session);
    }

    @GetMapping("/profile")
    public String profile(HttpSession session, Model model) {
        String redirect = checkAdminAndRedirect(session);
        if (redirect != null) {
            return redirect;
        }

        User sessionUser = AuthUtil.getCurrentUser(session);
        User currentUser = userRepository.findById(sessionUser.getId())
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 设置默认头像URL如果不存在
        if (currentUser.getAvatarUrl() == null ||
                currentUser.getAvatarUrl().isEmpty() ||
                !Files.exists(Paths.get("src/main/resources" + currentUser.getAvatarUrl()))) {
            currentUser.setAvatarUrl(DEFAULT_AVATAR);
            userRepository.save(currentUser); // 保存到数据库
        }

        model.addAttribute("avatarOptions", AVATAR_OPTIONS);
        model.addAttribute("currentUser", currentUser);
        return "admin/profile";
    }

    @PostMapping("/profile/select-avatar")
    public String selectAvatar(@RequestParam("avatarUrl") String avatarUrl,
                               HttpSession session,
                               RedirectAttributes redirectAttributes) {
        String redirect = checkAdminAndRedirect(session);
        if (redirect != null) {
            return redirect;
        }
        if (session.getAttribute("user") == null) {
            return "redirect:/login";
        }

        try {
            User sessionUser = (User) session.getAttribute("user");
            User currentUser = userRepository.findById(sessionUser.getId())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));

            boolean isValidAvatar = false;
            for (String option : AVATAR_OPTIONS) {
                if (option.equals(avatarUrl)) {
                    isValidAvatar = true;
                    break;
                }
            }

            if (isValidAvatar) { // 修复这里的逻辑错误
                currentUser.setAvatarUrl(avatarUrl);
                userRepository.save(currentUser);
                // 更新session中的用户信息
                session.setAttribute("user", currentUser);
                redirectAttributes.addFlashAttribute("success", "头像更新成功");
            } else {
                redirectAttributes.addFlashAttribute("error", "无效的头像选择");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "头像更新失败: " + e.getMessage());
        }
        
        return "redirect:/admin/profile";
    }

    //管理员主页
    @GetMapping("/interview_admin")
    public String adminHome(HttpSession session, Model model) {
        String redirect = checkAdminAndRedirect(session);
        if (redirect != null)
            return redirect;

    User currentUser = AuthUtil.getCurrentUser(session);
        model.addAttribute("currentUser", currentUser);

        List<User> allUsers  = userRepository.findAll();
        long totalUsers = allUsers.size();
        long adminUsers = allUsers.stream().filter(User::isAdmin).count();
        long regularUsers = totalUsers - adminUsers;

        model.addAttribute("totalUsers", totalUsers);
        model.addAttribute("adminUsers", adminUsers);
        model.addAttribute("regularUsers", regularUsers);

        return "admin/interview_admin";
    }

    // 用户管理主页
    @GetMapping("/users")
    public String usersManagement(HttpSession session, Model model) {
        String redirect = checkAdminAndRedirect(session);
        if (redirect != null)
            return redirect;

        if (session.getAttribute("user") == null) {
            return "redirect:/login";
        }

        List<User> users = userRepository.findAll();
        model.addAttribute("users", users);
        model.addAttribute("currentUser", session.getAttribute("user"));
        return "admin/users";
    }

    // 显示添加用户表单
    @GetMapping("/users/add")
    public String showAddUserForm(HttpSession session, Model model) {
        String redirect = checkAdminAndRedirect(session);
        if (redirect != null)
            return redirect;

        if (session.getAttribute("user") == null) {
            return "redirect:/login";
        }

        model.addAttribute("user", new User());
        return "admin/user-form";
    }

    // 显示编辑用户表单
    @GetMapping("/users/edit/{id}")
    public String showEditUserForm(@PathVariable Long id, HttpSession session, Model model) {
        String redirect = checkAdminAndRedirect(session);
        if (redirect != null)
            return redirect;

        if (session.getAttribute("user") == null) {
            return "redirect:/login";
        }

        Optional<User> user = userRepository.findById(id);
        if (user.isPresent()) {
            model.addAttribute("user", user.get());
            return "admin/user-form";
        } else {
            return "redirect:/admin/users";
        }
    }

    // 保存用户（添加或编辑）
    @PostMapping("/users/save")
    public String saveUser(@ModelAttribute User user, HttpSession session, RedirectAttributes redirectAttributes) {
        String  redirect = checkAdminAndRedirect(session);
        if (redirect != null)
            return redirect;

        if (session.getAttribute("user") == null) {
            return "redirect:/login";
        }

        try {
            if (user.getId() == null) {
                // 新用户
                user.setCreatedAt(LocalDateTime.now());
            }
            userRepository.save(user);
            redirectAttributes.addFlashAttribute("success", "用户保存成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "保存失败: " + e.getMessage());
        }

        return "redirect:/admin/users";
    }

    // 删除用户
    @GetMapping("/users/delete/{id}")
    public String deleteUser(@PathVariable Long id, HttpSession session, RedirectAttributes redirectAttributes) {
        String  redirect = checkAdminAndRedirect(session);
        if (redirect != null)
            return redirect;
        if (session.getAttribute("user") == null) {
            return "redirect:/login";
        }

        try {
            userRepository.deleteById(id);
            redirectAttributes.addFlashAttribute("success", "用户删除成功");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除失败: " + e.getMessage());
        }

        return "redirect:/admin/users";
    }
}